package com.op.studyingliteapp.sender.ui.view;

import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.drawable.BitmapDrawable;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.PopupWindow;
import android.widget.RadioGroup;
import com.op.polites.android.GestureImageView;
import com.op.studyingliteapp.R;
import com.op.studyingliteapp.fragment.viewer.PDFAdapter;
import com.op.studyingliteapp.sender.listener.onDrawListener;
import com.op.util.ScreenSendUtils;

import java.util.ArrayList;

/**
 * Created by Genji on 2015/7/10.
 */
public class BrushesView extends PopupWindow implements OnClickListener, View.OnTouchListener, ViewPager.OnPageChangeListener {

    private static final String TAG = BrushesView.class.getSimpleName();

    private Button button;
    private BasicViewPager basicViewPager;
    private float mX;
    private float mY;
    private static Paint mGesturePaint; // 画笔
    private static Path mPath = new Path(); // 路径
    private static int colorMUN = R.id.red;
    private static int modeMUN = 13;//画笔的大小
    private RadioGroup radioGroup;//颜色
    private RadioGroup moderadioGroup;//选择画笔大小
    private Button clearScreen;//清除屏幕的按钮
    private Button goBackMovePdf;//从画笔回到pdf的画面移动
    private View contentView;
    private int index;
    private PDFAdapter pdfAdapter;

    public BrushesView(View contentView, int width, int height, Button button) {
        super(contentView, width, height);
        init(contentView);
        this.button = button;
        this.button.setOnClickListener(this);

    }

    public BrushesView(View contentView, int width, int height) {
        super(contentView, width, height);
        init(contentView);

    }

    @Override
    public void onClick(View v) {
        this.button.setBackgroundResource(R.drawable.paint_brush_normal);
        stopScroll();
        getCurrentItem().unableGesture();
        getCurrentItem().getParent().requestDisallowInterceptTouchEvent(true);
        int[] location = new int[2];
        this.button.getLocationOnScreen(location);
        this.showAtLocation(this.button,Gravity.NO_GRAVITY,location[0]-this.getWidth(),location[1]);

        getCurrentItem().setOnTouchListener(this);
        getCurrentItem().setOnDrawListener(new onDrawListener() {
            @Override
            public void drawEnd(Canvas canvas) {
                paint(canvas);
            }
        });
        Log.i("xxx", getCurrentItem().getId() + "");
    }


    public void associate(BasicViewPager basicViewPager) {
        this.basicViewPager = basicViewPager;
        this.basicViewPager.setOnPageChangeListener(this);
        this.pdfAdapter =(PDFAdapter)this.basicViewPager.getAdapter();
    }



    @Override
    public boolean onTouch(View v, MotionEvent event) {
        Log.i("BrushesView", "onTouch");
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                mPath = new Path();
                colorSelection(modeMUN, colorMUN);//大小，颜色
                // setsetmodeMUN(modeMUN,colorSelection(modeMUN));
                touchDown(event);
                break;
            case MotionEvent.ACTION_MOVE:
                touchMove(event);
                pathList.add(mPath);
                paintList.add(mGesturePaint);
                break;
            case MotionEvent.ACTION_UP:
                pathList.add(mPath);
                paintList.add(mGesturePaint);
                break;
        }
        // 更新绘制
//        g.invalidate();
        getCurrentItem().invalidate();
        if (event.getAction() == MotionEvent.ACTION_UP) {
            ScreenSendUtils.send(basicViewPager); // 用于投影
        }

        return true;
//        return false;

    }

    // 手指点下屏幕时调用
    private void touchDown(MotionEvent event) {

//		 mPath.rewind();
        // 重置绘制路线，即隐藏之前绘制的轨迹
//		 mPath.reset(); //清除之前画的
        float x = event.getX();
        float y = event.getY();

        mX = x;
        mY = y;
        // mPath绘制的绘制起点
        mPath.moveTo(x, y);
    }


    // 手指在屏幕上滑动时调用
    private void touchMove(MotionEvent event) {
        final float x = event.getX();
        final float y = event.getY();

        final float previousX = mX;
        final float previousY = mY;

        final float dx = Math.abs(x - previousX); // 取绝对值
        final float dy = Math.abs(y - previousY);

        // 两点之间的距离大于等于3时，生成贝塞尔绘制曲线
        if (dx >= 3 || dy >= 3) {
            // 设置贝塞尔曲线的操作点为起点和终点的一半
            float cX = (x + previousX) / 2;
            float cY = (y + previousY) / 2;

            // 二次贝塞尔，实现平滑曲线；previousX, previousY为操作点，cX, cY为终点
            mPath.quadTo(previousX, previousY, cX, cY);

            // 第二次执行时，第一次结束调用的坐标值将作为第二次调用的初始坐标值
            mX = x;
            mY = y;
        }
    }

    public static void setmGesturePaintColor(int color) {
        colorMUN = color;
    }

    public static void setmodeMUN(int mode) {
        modeMUN = mode;//画笔大小
        Log.i("画笔大小", String.valueOf(modeMUN));
    }

    //先保留，有点逻辑问题
    private void setsetmodeMUN(int mode, int color) {
        mGesturePaint = createPaint(mode, color);
    }

    private void colorSelection(int mode, int color) {

        Log.i("画笔大小2", String.valueOf(mode));
        switch (color) {
            case R.id.green:
                mGesturePaint = createPaint(mode, Color.rgb(81, 207, 45));
                break;
            case R.id.red:
                mGesturePaint = createPaint(mode, Color.rgb(255, 19, 19));
                break;
            case R.id.blue:
                mGesturePaint = createPaint(mode, Color.rgb(48, 143, 161));
                break;
            case R.id.black:
                mGesturePaint = createPaint(mode, Color.rgb(37, 37, 37));
                break;
            default:
        }

    }

    public void reset() {
        paintList.clear();
        pathList.clear();
        getCurrentItem().invalidate();

        Log.i("画笔是否为空？", String.valueOf(paintList.size()));
        Log.i("路径是否为空？", String.valueOf(pathList.size()));
    }

    private Paint createPaint(int width, int color) {
        Paint paint = new Paint();
        paint.setAntiAlias(true);
        paint.setStyle(Paint.Style.STROKE);
        paint.setStrokeWidth(width);
        paint.setColor(color);
        return paint;
    }

    private void beginScroll() {
        this.basicViewPager.setCanScroll(true);


    }

    private void stopScroll() {
        this.basicViewPager.setCanScroll(false);


    }

    ArrayList<Paint> paintList = new ArrayList<Paint>();
    ArrayList<Path> pathList = new ArrayList<Path>();

    private void init(View contentView) {
        this.contentView = contentView;
        mGesturePaint = createPaint(13, Color.rgb(255, 19, 19));
        this.setBackgroundDrawable(new BitmapDrawable());//这个不能删
        this.setFocusable(false);//修正
        this.setOutsideTouchable(true);

        this.radioGroup = (RadioGroup) contentView.findViewById(R.id.pen_color);
        this.moderadioGroup = (RadioGroup) contentView.findViewById(R.id.pen_mode);
        this.clearScreen = (Button) contentView.findViewById(R.id.cleer);
        this.goBackMovePdf = (Button) contentView.findViewById(R.id.hand1);

        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                setmGesturePaintColor(checkedId);
            }

        });
        //谁把这个删了。。。
        clearScreen.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                reset();
                getCurrentItem().invalidate();
            }
        });
        moderadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId) {
                    case R.id.big:
                        setmodeMUN(21);
                        break;
                    case R.id.middle:
                        setmodeMUN(13);
                        break;
                    case R.id.small:
                        setmodeMUN(7);
                        break;
                    default:
                        break;
                }
            }
        });
        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {

                switch (checkedId) {
                    case R.id.green:
                        setmGesturePaintColor(R.id.green);
                        break;
                    case R.id.red:
                        setmGesturePaintColor(R.id.red);
                        break;
                    case R.id.black:
                        setmGesturePaintColor(R.id.black);
                        break;
                    case R.id.blue:
                        setmGesturePaintColor(R.id.blue);
                        break;

                    default:
                }
            }

        });

        goBackMovePdf.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                button.setBackgroundResource(R.drawable.hand_selected);
                beginScroll();
                   getCurrentItem().ableGesture();
//                basicViewPager.isCanScroll=true;
                getCurrentItem().getParent().requestDisallowInterceptTouchEvent(false);
                getCurrentItem().setOnTouchListener(null);
                dismiss();
            }
        });

    }

    public void paint(Canvas canvas) {
        Log.i("paint", "paint");
        for (int i = 0; i < pathList.size(); i++) {
            canvas.drawPath(pathList.get(i), paintList.get(i));
        }
    }

    @Override
    public void onPageScrolled(int i, float v, int i1) {
    }

    @Override
    public void onPageSelected(int i) {
        index = i;
        Log.i(TAG, "onPageSelected : " + i);
        if (getCurrentItem().isLoadCompleted()) {
            Log.i(TAG, "LoadCompleted : " + i+" sending ");
        }


    }

    @Override
    public void onPageScrollStateChanged(int i) {
        switch (i) {
            case ViewPager.SCROLL_STATE_DRAGGING:
                reset(); // 滑动viewpager就清空画笔
                break;

            default:
                break;
        }
    }

    /**
     * 得到当前的GestureImageView //
     */
    public GestureImageView getCurrentItem() {
        return (GestureImageView) basicViewPager.findViewById(index);
    }

}
